package com.shengqin.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.layout.font.FontProvider;
import com.lowagie.text.pdf.BaseFont;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.*;
import java.nio.file.Files;
import java.util.List;

@Slf4j
public class PdfUtil {
    public static final String FONT = "/data/fonts/simsun.ttc";

    /**
     * HTML 转 PDF
     * @param outPath 输出pdf路径
     * @return 是否创建成功
     */
    public static boolean html2Pdf(List<String> htmlStrList, String outPath) {
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            try {
                ConverterProperties converterProperties = new ConverterProperties();
                converterProperties.setCharset("UTF-8");

                ITextRenderer renderer = new ITextRenderer();
                ITextFontResolver fontResolver = renderer.getFontResolver();
                try {
                    //设置字体，否则不支持中文,在html中使用字体，html{ font-family: SimSun;}
                    fontResolver.addFont("font/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                } catch (IOException e) {
                    log.error(e.getMessage());
                }

                renderer.setDocumentFromString(htmlStrList.get(0));
                renderer.layout();
                renderer.createPDF(outputStream, false);

                for (int i = 1; i < htmlStrList.size(); i++) {
                    renderer.setDocumentFromString(htmlStrList.get(i));
                    renderer.layout();
                    renderer.writeNextDocument(i);
                }

                renderer.finishPDF();

                File file = new File(outPath);
                try (FileOutputStream outStream = new FileOutputStream(file)) {
                    byte[] bytes = outputStream.toByteArray();
                    outStream.write(bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    // 关闭输出流
                    outputStream.close();
                }

            } catch (Exception e) {
                log.error("生成 PDF 失败", e);
            }
        } catch (Exception e) {
            log.error("生成模板内容失败", e);
            return false;
        }
        return true;
    }

    private static byte[] createQrCode(String text){
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
        try {
            BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, 100, 100);
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
            return pngOutputStream.toByteArray();
        } catch (IOException | WriterException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * HTML 转 PDF
     *
     * @param content html内容
     * @return PDF字节数组
     */
    public static byte[] html2Pdf(String content) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ConverterProperties converterProperties = new ConverterProperties();
            converterProperties.setCharset("UTF-8");
            FontProvider fontProvider = new FontProvider();
            PdfFont font = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H");
            fontProvider.addFont(font.getFontProgram(), "UniGB-UCS2-H");
            converterProperties.setFontProvider(fontProvider);
            HtmlConverter.convertToPdf(content, outputStream, converterProperties);
        } catch (Exception e) {
            log.error("生成 PDF 失败", e);
        }
        return outputStream.toByteArray();
    }

    public static byte[] html2Pdf(List<String> htmlStrList) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ITextRenderer renderer = new ITextRenderer();
            ITextFontResolver fontResolver = renderer.getFontResolver();
            try {
                //设置字体，否则不支持中文,在html中使用字体，html{ font-family: SimSun;}
                fontResolver.addFont("font/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            } catch (IOException e) {
                log.error(e.getMessage());
            }

            renderer.setDocumentFromString(htmlStrList.get(0));
            renderer.layout();

            renderer.createPDF(outputStream, false);

            for (int i = 1; i < htmlStrList.size(); i++) {
                renderer.setDocumentFromString(htmlStrList.get(i));
                renderer.layout();
                renderer.writeNextDocument(i);
            }

            renderer.finishPDF();

        } catch (Exception e) {
            log.error("生成 PDF 失败", e);
        }
        return outputStream.toByteArray();
    }

    public static String getFileAbsolutePath(String templatePath, String createPath, boolean isConvered) {
        try {
            // 创建临时文件，获取jar里面的配置文件
            File file = new File(createPath);
            if (file.exists() && !isConvered) {
                return file.getAbsolutePath();
            }
            InputStream inputStream = null;
            try {
                ClassPathResource resource = new ClassPathResource(templatePath);
                inputStream = resource.getInputStream();
                byte[] buffer = new byte[inputStream.available()];
                inputStream.read(buffer);
                OutputStream outStream = Files.newOutputStream(file.toPath());
                outStream.write(buffer);
                return file.getAbsolutePath();
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
        } catch (Exception e) {
            System.out.println("FileUtil getFilePath Fail cause by:" + e);
        }
        return null;
    }
}
